package org.example.common.session;

import cn.hutool.core.lang.Pair;
import cn.hutool.core.text.CharSequenceUtil;
import lombok.extern.slf4j.Slf4j;
import org.example.common.configs.exception.WGException;
import org.example.common.enums.WGErrorEnum;
import org.example.model.dto.FullUserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @author weigang
 * @create 2022-11-08 14:49
 */
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private SessionStore sessionStore;


    /**
     * 在请求处理之前进行调用（Controller方法调用之前）
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 获取token
        String token = request.getHeader("token");
        log.info("preHandle Intercept Controller , token : [{}]" , token);
        if (CharSequenceUtil.isEmpty(token)) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            throw new WGException(WGErrorEnum.e_0025);
        }

        Pair<String, FullUserDto> session = sessionStore.getIfPresent(token);
        if (Objects.isNull(session) || Objects.isNull(session.getValue())) {
            throw new WGException(WGErrorEnum.e_1026.getCode(), WGErrorEnum.e_1026.getMsg());
        }

        UserContext.putUser(session);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        UserContext.clear();
    }

}
